/**
 * Project Name:ulewo-web
 * File Name:CommentController.java
 * Package Name:com.ulewo.controller
 * Date:2015年11月2日下午9:30:38
 * Copyright (c) 2015, ulewo.com All Rights Reserved.
 */

package com.ulewo.api.controller;

import ch.qos.logback.core.joran.util.StringToObjectConverter;
import com.ulewo.controller.BaseController;
import com.ulewo.exception.BusinessException;
import com.ulewo.po.enums.ArticleType;
import com.ulewo.po.enums.DateTimePatternEnum;
import com.ulewo.po.enums.ResponseCode;
import com.ulewo.po.model.Comment;
import com.ulewo.po.model.SpitSlot;
import com.ulewo.po.model.SpitSlotComment;
import com.ulewo.po.query.CommentQuery;
import com.ulewo.po.query.SpitSlotQuery;
import com.ulewo.po.vo.AjaxResponse;
import com.ulewo.po.vo.PaginationResult;
import com.ulewo.po.vo.api.SpitSlotCommentVO;
import com.ulewo.po.vo.api.SpitSlotVO;
import com.ulewo.service.CommentService;
import com.ulewo.service.SpitSlotService;
import com.ulewo.utils.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.HttpRequest;
import org.apache.solr.common.util.Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class ApiSpitSlotController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(ApiSpitSlotController.class);

    @Resource
    private SpitSlotService spitSlotService;

    private final static int MAX_FILE_MAX = 1024 * 1024 * 3;

    /**
     * 加载评论
     * @param pageNo
     * @return
     */
    @ResponseBody
    @RequestMapping("loadSpitslot")
    public AjaxResponse<PaginationResult<SpitSlotVO>> loadSpitslot(Integer pageNo) {
        AjaxResponse<PaginationResult<SpitSlotVO>> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {
            SpitSlotQuery query = new SpitSlotQuery();
            query.setPageNo(pageNo);
            PaginationResult<SpitSlot> paginationResult = spitSlotService.findSpitSlotListNoComment(query);
            PaginationResult<SpitSlotVO> voResult = new PaginationResult<>(paginationResult.getPage(), SpitSlot.convert2VOList
                    (paginationResult.getList()));
            result.setData(voResult);
        } catch (Exception e) {
            logger.error("api获取吐槽信息异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("系统异常");
        }
        return result;
    }

    /**
     * 吐槽详情
     * @param session
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("spitslotDetail")
    public AjaxResponse<SpitSlotVO> spitslotDetail(HttpSession session, Integer id) {
        AjaxResponse<SpitSlotVO> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {
            SpitSlot spitSlot = spitSlotService.findSpitSlotNoCommentById(id);
            if (spitSlot == null) {
                result.setResponseCode(ResponseCode.BUSINESSERROR);
                result.setErrorMsg("吐槽不存在");
                return result;
            }
            SpitSlotVO vo = SpitSlot.convert2VO(spitSlot);
            vo.setCommentList(SpitSlotComment.convert2VOList(spitSlotService.loadSpitSlotComment(id)));
            result.setData(vo);
        } catch (Exception e) {
            logger.error("api获取吐槽信息异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("系统异常");
        }
        return result;
    }

    /**
     * 发布吐槽
     * @param session
     * @param files
     * @return
     */

    @ResponseBody
    @RequestMapping("postSpitslot.action")
    public AjaxResponse<SpitSlotVO> postSpitslot(HttpSession session, HttpServletRequest request, String content,
                                                 String images, String sourceFrom) {
        AjaxResponse<SpitSlotVO> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        try {

            if (StringTools.filterEmoji(content)) {
                throw new BusinessException("系统不允许插入emoji表情");
            }

            if (!StringTools.isEmpty(images)) {
                String[] imageArray = images.split("\\|");
                if (imageArray.length > 3) {
                    throw new BusinessException("最多只能上传三张图片");
                }
                for (String img : imageArray) {
                    if (!StringTools.isEmpty(img)) {
                        ImageUtils.copyTemp2Real(img);
                    }
                }
            }
            SpitSlot spitSlot = new SpitSlot();
            spitSlot.setContent(content);
            spitSlot.setImageUrl(images);
            this.setUserBaseInfo(SpitSlot.class, spitSlot, session);
            spitSlot.setSourceFrom(sourceFrom);
            spitSlotService.addSpitSlot(spitSlot);
            result.setData(SpitSlot.convert2VO(spitSlot));
        } catch (BusinessException e) {
            logger.error("api添加吐槽信息异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("api添加吐槽信息异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("系统异常");
        }
        return result;
    }

    /*@ResponseBody
    @RequestMapping("postSpitslot.action")
    public AjaxResponse<SpitSlot> postSpitslot(HttpSession session, HttpServletRequest request, String content,
                                               @RequestParam(required = false) MultipartFile[] files) {
        AjaxResponse<SpitSlot> result = new AjaxResponse<>();
        result.setResponseCode(ResponseCode.SUCCESS);
        StringBuilder images = new StringBuilder();
        try {
            String realPath = ServerUtils.getImageFolder();
            //上传图片
            if (files != null && files.length > 0) {
                if (files.length > 3) {
                    result.setResponseCode(ResponseCode.BUSINESSERROR);
                    result.setErrorMsg("最多只能上传三张图片");
                    return result;
                }
                for (MultipartFile multipartFile : files) {
                    long size = multipartFile.getSize();
                    if (size > MAX_FILE_MAX) {
                        result.setResponseCode(ResponseCode.BUSINESSERROR);
                        result.setErrorMsg("文件不能超过3M");
                        return result;
                    }
                    String fileName = multipartFile.getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if (!"JPG".equalsIgnoreCase(suffix) && !"PNG".equalsIgnoreCase(suffix) && !"gif".equalsIgnoreCase
                            (suffix) && !"BMP".equalsIgnoreCase(suffix)) {
                        result.setResponseCode(ResponseCode.BUSINESSERROR);
                        result.setErrorMsg("文件类型只能是图片");
                        return result;
                    }
                    String current = String.valueOf(System.currentTimeMillis());
                    fileName = current + "." + suffix;
                    String saveDir = DateUtil.format(new Date(), DateTimePatternEnum.YYYYMM.getPattern());
                    String savePath = saveDir + "/" + fileName;
                    String fileDir = realPath + saveDir;
                    File dir = new File(fileDir);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    String filePath = fileDir + "/" + fileName;
                    File file = new File(filePath);
                    multipartFile.transferTo(file);
                    if (size > MAX_FILE_MAX && !"gif".equalsIgnoreCase(suffix)) {
                        BufferedImage src = ImageIO.read(file);
                        BufferedImage dst = ScaleFilter.filter4Height(src, src.getWidth());
                        ImageIO.write(dst, "JPEG", file);
                    }
                    images.append(savePath).append("|");
                }
            }
            String resultImage = images.toString();
            if (!StringTools.isEmpty(resultImage)) {
                resultImage = resultImage.substring(0, resultImage.lastIndexOf("|"));
            }
            SpitSlot spitSlot = new SpitSlot();
            spitSlot.setContent(content);
            spitSlot.setImageUrl(resultImage);
            this.setUserBaseInfo(SpitSlot.class, spitSlot, session);
            spitSlotService.addSpitSlot(spitSlot);
            result.setData(spitSlot);
        } catch (BusinessException e) {
            logger.error("api添加吐槽信息异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("api添加吐槽信息异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("系统异常");
        }
        return result;
    }*/

    /**
     * 发布评论
     * @param session
     * @param spitSlotId
     * @param content
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addSpitSlotComment.action")
    public AjaxResponse<SpitSlotCommentVO> addSpitSlotComment(HttpSession session, Integer spitSlotId, String content, String sourceFrom) {
        AjaxResponse<SpitSlotCommentVO> result = new AjaxResponse<SpitSlotCommentVO>();
        try {
            if (StringTools.filterEmoji(content)) {
                throw new BusinessException("系统不允许插入emoji表情");
            }
            SpitSlotComment comment = new SpitSlotComment();
            comment.setContent(content);
            comment.setSpitSlotId(spitSlotId);
            this.setUserBaseInfo(SpitSlotComment.class, comment, session);
            comment.setSourceFrom(sourceFrom);
            spitSlotService.addSpitSlotComment(comment);
            result.setData(SpitSlotComment.convert2VO(comment));
            result.setResponseCode(ResponseCode.SUCCESS);
        } catch (BusinessException e) {
            logger.error("api发表吐槽评论异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("api发表吐槽评论异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("发表吐槽评论异常");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "base64ImageUpload.action")
    public AjaxResponse<String> base64ImageUpload(String base64Image, String imageSuffix) {
        AjaxResponse<String> result = new AjaxResponse<String>();
        OutputStream out = null;
        try {
            String realPath = ServerUtils.getImageFolder();

            if (StringTools.isEmpty(base64Image)) {//图像数据为空
                result.setResponseCode(ResponseCode.BUSINESSERROR);
                result.setErrorMsg("图片base64编码不能为空");
                return result;
            }
            base64Image = base64Image.replace("data:image/jpeg;base64,", "");

            BASE64Decoder decoder = new BASE64Decoder();
            //Base64解码
            byte[] b = decoder.decodeBuffer(base64Image);

            if (b.length > Constants.SIZE_1_M) {
                result.setResponseCode(ResponseCode.BUSINESSERROR);
                result.setErrorMsg("图片不能超过1M");
                return result;
            }

            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            String current = String.valueOf(System.currentTimeMillis());
            String fileName = current + "." + imageSuffix;
            String saveDir = DateUtil.format(new Date(), DateTimePatternEnum.YYYYMM.getPattern());
            String savePath = saveDir + "/" + fileName;
            String fileDir = realPath + Constants.PATH_TEMP_UPLOAD + saveDir;
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String filePath = fileDir + "/" + fileName;
            out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            result.setResponseCode(ResponseCode.SUCCESS);
            result.setData(savePath);
            return result;
        } catch (Exception e) {
            logger.error("图片上传异常", e);
            result.setResponseCode(ResponseCode.SERVERERROR);
            result.setErrorMsg("图片上传异常");
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
